package com.example.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Description: redis 工具类
 * @Author: mingtian
 * @CreateDate: 2019/11/15 16:41
 * @Version: 1.0
 */
@Slf4j
@Component
public class StringRedisTemplateUtil {

    /**
     * 超时时间
     */
    public static final Long TIME_OUT = 3600L;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 存储
     *
     * @param key
     * @param value
     * @param timeOut
     */
    public void add(String key, String value, Long timeOut) {
        redisTemplate.opsForValue().set(key, value);
        if (timeOut != null) {
            Boolean expire = redisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
            log.info("expire:{}", expire);
        }
    }


    /**
     * 根据 key 获取 value
     *
     * @param key
     * @return
     */
    public String getByKey(String key) {
        if (StringUtils.isEmpty(key)) {
            return "key is empty! ";
        }
        String s = redisTemplate.opsForValue().get(key);
        return s;
    }

    /**
     * 根据 key  将 value + n 操作
     *
     * @param key
     * @param value
     * @return
     */
    public Long increment(String key, Long value) {
        return redisTemplate.opsForValue().increment(key, value);
    }

    /**
     * 根据 key  将 value - n 操作
     *
     * @param key
     * @param value
     * @return
     */
    public Long decrement(String key, Long value) {
        return redisTemplate.opsForValue().decrement(key, value);
    }
}